package com.dudu.dao;

import java.sql.Connection;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mortbay.log.Log;

import com.dudu.model.PushToCusRecord;

import core.CoreDao;
import core.db.DBConnectionUtil;

public class PushCallRecordDao {
	private static final Logger log =  core.util.Logger.getLogger(PushCallRecordDao.class.getSimpleName());
	/**
	 * 新增，ImsConsumeRecordThread使用
	 * @param dao
	 * @param bean
	 * @return
	 */
	public int insert(CoreDao dao, PushToCusRecord bean) {

		Connection con = null;
		int result = -1;
		try {
			
			con = DBConnectionUtil.getDBConnection("emate1");
			
			StringBuffer sql = new StringBuffer(
					"INSERT INTO t_push_ticket(" +
					"record_url, meet_id, session_id, begin_time,end_time, " +
					"caller, callee, displaynbr,time,status," +
					"pid,send_count,note,code," +
					"app_key,cust_account,account_identify,product_key,periphery_code," +
					"ability_type,user_identify)");
			
			sql.append(" VALUES(" +
					"?, ?, ?, ?, ?, " +
					"?, ?,?, ?, ?, " +
					"?, ?, ?, ?, " +
					"?, ?,?, ?, ?, " +
					"?,?)");
			
			List<JSONObject> list = dao.serviceJsonSql(
					con,
					sql.toString(),
					new Object[] {
						bean.getRecord_url(), bean.getMeet_id(), bean.getSession_id(), bean.getBegin_time(), bean.getEnd_time(),
						bean.getCaller(), bean.getCallee(), bean.getDisplaynbr(), bean.getTime(), bean.getStatus(),
						bean.getPid(), bean.getSend_count(), bean.getNote(), bean.getCode(),
						bean.getApp_key(), bean.getCust_account(), bean.getAccount_identify(), bean.getProduct_key(), bean.getPeriphery_code(),
						bean.getAbility_type(),bean.getUser_identifer()
					});

			if(list != null && list.size()>0){

				JSONObject obj = list.get(0);
				result = obj.optInt("result");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	/**
	 * 根据sessionId查询推送列表
	 * @param dao
	 * @param sessionId
	 * @param caller
	 * @param callee
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public List<PushToCusRecord> queryPushToCusRecordBySessionId(CoreDao dao,
			String sessionId,String caller,String callee,String beginTime,String endTime) {

		Connection con = null;
		List<PushToCusRecord> result = null;
		
		try {
			
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer();
			
			/*sql.append(" select acc.parent_accountIdentify as app_identify,acc.callback_url as recordUrl,acc.custAccount as cust_account,");
			sql.append(" acc.product_code as product_code,");
			sql.append(" detail.id as detailId,detail.session_id,detail.beginTime,detail.endTime,");
			sql.append("  detail.caller,detail.callee,detail.displaynbr,detail.time,detail.ability_type");
			sql.append(" ,com.identify as com_identify,cuser.user_identifer");
			
			sql.append(" from t_meet_ims ims,");
			sql.append(" (select * from t_meet_ims_callback callback where callback.session_id=? " +
					" and callback.caller=? and callback.callee=? and callback.beginTime=? and endTime=?) detail ,");
			sql.append(" t_company com,");
			sql.append(" t_company_user cuser,");
			sql.append(" t_account acc");
			
			sql.append(" where ims.call_identifier = detail.session_id ");
			sql.append(" and ims.user_id = cuser.id ");
			sql.append(" and ims.company_id = com.id");
			sql.append(" and ims.account_id = acc.id");*/
			sql.append(" select acc.url_ticket as record_url, acc.cust_account, acc.cust_account as account_identify,");
			sql.append(" detail.id as meet_id,detail.session_id,detail.beginTime as begin_time,detail.endTime as end_time,");
			sql.append(" detail.caller,detail.callee,detail.displaynbr,detail.time,detail.ability_type,");
			sql.append("  ims.app_key as app_key,");
			sql.append(" ims.periphery_code as product_key,ims.periphery_code as periphery_code, ims.user_identify as user_identifer");
			
			sql.append(" from t_meet_info ims,");
			sql.append(" (select * from t_meet_ims_callback callback where callback.session_id=? " +
					" and callback.caller=? and callback.callee=? and callback.beginTime=? and endTime=?) detail ,");
			sql.append(" t_account_extend acc");
			
			sql.append(" where ims.session_id = detail.session_id ");
			sql.append(" and ims.cust_account = acc.cust_account");
			
			
			List<JSONObject> list = dao.serviceJsonSql(con, sql.toString(),new Object[] {
				
				sessionId,
				caller,
				callee,
				beginTime,
				endTime
				
			});
			
			if (list != null && list.size() > 0) {
				result = dao.covertToBean(list, PushToCusRecord.class);
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		
		return result;
	}
	/**
	 * 根据拼接的查询条件查询推送失败的话单记录
	 * @param dao
	 * @param pageSql
	 * @param paramSql
	 * @return
	 */
	public List<PushToCusRecord> queryPushFailed(CoreDao dao, String pageSql, String paramSql) {
		log.info("PushCallRecordDao.queryPushFailed");
		if(StringUtils.isNotBlank(paramSql)){
			paramSql = " and " + paramSql;
		}else{
			paramSql="";
		}
		Connection con = null;
		List<PushToCusRecord> result = null;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer("SELECT * FROM t_push_ticket tpcr  WHERE tpcr.`status`='1' ");
			sql.append(paramSql);
			sql.append(" ORDER BY tpcr.end_time DESC ");// 根据结束时间倒序
			sql.append(pageSql);
			log.info("queryPushFailed="+sql);
			
			List<JSONObject> list = dao.serviceJsonSql(con, sql.toString(), new Object[] { });

			if (list != null && list.size() > 0) {
				result = dao.covertToBean(list, PushToCusRecord.class);
			}

		} catch (Exception ex) {
			Log.warn("根据拼接的查询条件查询推送失败的话单记录信息出错"+ex);
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	/**
	 * 获取推送失败的话单的条数
	 * @param dao
	 * @param paramSql
	 * @return
	 */
	public int getTotalUnpush(CoreDao dao, String paramSql) {
		log.info("PushCallRecordDao.getTotalUnpush");
		if(StringUtils.isNotBlank(paramSql)){
			paramSql = " and " + paramSql;
		}else{
			paramSql="";
		}
		Connection con = null;
		int result = -1;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer("select count(1) as totalUnpush from t_push_ticket tpcr where  tpcr.`status`='1'");
			sql.append(paramSql);
			log.info("getTotalUnpush="+sql.toString());
			List<JSONObject> list = dao.serviceJsonSql(
					con,
					sql.toString(),
					new Object[] { });

			JSONObject obj = list.get(0);
			result = (Integer) obj.get("totalUnpush");
			

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	/**
	 * 向第三方重推话单：根据id，更改status状态为0；清空pid，note，code
	 * @param dao
	 * @param bean
	 * @return
	 */
	public int updateStatusPidNoteCode(CoreDao dao, String id) {
		log.info("PushCallRecordDao.updateStatusPidNoteCode");
		Connection con = null;
		int result = -1;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer(
					" update t_push_ticket set status='0',pid='',note='',code='' where id=? " );

			List<JSONObject> list = dao.serviceJsonSql(
					con,
					sql.toString(),
					new Object[] { id });

			JSONObject obj = list.get(0);
			result = obj.optInt("result");

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
}
